<template>
  <div class="clock">
    <div class="date" v-text="data.date.value"/>
    <div class="time" v-text="data.time.value"/>
  </div>
</template>
<script>
import {defineComponent, ref} from 'vue'

export default defineComponent({
  name: 'Clock',
  components: {},
  setup() {
    const data = {
      count: ref(0),
      time: ref('00:00:00'),
      startTime: new Date().getTime(),
      date: ref('0000-00-00 周X'),
      week: ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    }
    const updateTenseText = hours => hours > 12 ? "P.M" : "A.M"
    const updateTenseHours = hours => hours > 10 ? hours - 12 : hours
    const timingProcessing = () => {
      data.count.value++
      let nextTime = 1000 - new Date().getTime() - (data.startTime + data.count * 1000)
      setTimeout(updateTime, nextTime < 0 ? 0 : nextTime)
    }
    const updateTime = () => {
      timingProcessing()
      const current = new Date()
      data.date.value = `${zeroPadding(current.getFullYear(), 4)}-${zeroPadding(current.getMonth() + 1, 2)}-${zeroPadding(current.getDate(), 2)} ${data.week[current.getDay()]}`
      data.time.value = `${updateTenseText(current.getHours())} ${zeroPadding(updateTenseHours(current.getHours()), 2)}:${zeroPadding(current.getMinutes(), 2)}:${zeroPadding(current.getSeconds(), 2)}`
    }
    const zeroPadding = (num, digit) => {
      let zero = '';
      for (let i = 0; i < digit; i++) {
        zero += '0';
      }
      return (zero + num).slice(-digit)
    }
    updateTime() && setTimeout(updateTime, 1000)
    return {
      data
    }
  }
})
</script>
<style lang="scss" scoped>
.clock {
  width: 130px;
  height: 40px;
  display: flex;
  color: #daf6ff;
  cursor: default;
  flex-flow: column;
  line-height: 40px;
  border-radius: 3px;
  text-align: center;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease-in-out;
  background: rgba(15, 84, 131, 0.85);
  box-shadow: 2px 2px 6px rgb(31 135 185 / 70%);

  .date, .time {
    margin: 0;
    padding: 0;
    height: 20px;
    line-height: 20px;
    user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
  }

  .time {
    font-size: 15px;
    letter-spacing: 0.05em;
  }

  .date {
    font-size: 10px;
    letter-spacing: 0.1em;
  }
}
</style>
